/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Control;

import java.awt.Component;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigInteger;
import java.net.URL;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.net.ssl.SSLServerSocketFactory;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;

/**
 *
 * @author Augusto Wolf
 */
public class UTI {

    public final static DateFormat formatterSQL = new SimpleDateFormat("yyyy-MM-dd");
    public final static DateFormat formatterSQL1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public final static DateFormat formatterDATA = new SimpleDateFormat("dd/MM/yyyy");
    public final static DateFormat formatterDATAeHORA = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    public final static DateFormat formatterDATA1 = new SimpleDateFormat("yyyy/MM/dd");
    public final static DateFormat formatterDATAhora = new SimpleDateFormat("HH:mm:ss");
    public final static DateFormat formatterDATAhora1 = new SimpleDateFormat("HH:mm");
    private static int key = 2;

    public static int testarSenha(String contents) {
        //String fullRegex = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
        String[] partialRegexChecks = {
            ".*[a-z]+.*",
            ".*[A-Z]+.*",
            ".*[\\d]+.*",
            ".*[@#$%]+.*"
        };
       String[] qualifiers = {
            "Lower case letters",
            "Upper case letters",
            "Digits [0-9]",
            "Symbols: $ % # @",
            "Length: 6-20 characters"
        };
        int numCompleted = 0;
        contents = contents.trim();
        int length = contents.length();
        double total = 5;

        //partial matching
        for (int i = 0; i < partialRegexChecks.length; i++) {
            System.out.print(qualifiers[i]);
            if (contents.matches(partialRegexChecks[i])) {
                System.out.println(" OK");
                numCompleted++;
            } else {
            }
        }
        if (length >= 10) {
            // System.out.println("Length between 6 and 20");
            numCompleted++;
        } else {
        }
        //full matching
        // if (contents.matches(fullRegex)) {
        // } else {
        // }
        return numCompleted;
    }

    public static boolean validaLDAP(String usuario, String senha, String host, int porta, boolean ssl) {
        DirContext contexto = null;
        if (porta == 0) {
            porta = 389;
        }

        try {
            Hashtable props = new Hashtable(11);

            props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

            if (ssl) {
                props.put(Context.PROVIDER_URL, "ldap://" + host + ":" + porta + "");
                props.put(Context.SECURITY_PROTOCOL, "ssl");
                props.put(Context.SECURITY_AUTHENTICATION, "EXTERNAL");

                System.setProperty("javax.net.ssl.keyStore", "ctti1");
                System.setProperty("javax.net.ssl.trustStorePassword", "ctti2011");

            } else {
                props.put(Context.PROVIDER_URL, "ldap://" + host + ":" + porta + "");
                props.put(Context.SECURITY_AUTHENTICATION, "simple");
            }

            props.put(Context.SECURITY_PRINCIPAL, usuario);
            props.put(Context.SECURITY_CREDENTIALS, senha);

            SSLServerSocketFactory.getDefault();

            DirContext ctx = new InitialDirContext(props);


            contexto = ctx;
            Attributes attrs = ctx.getAttributes(usuario);

            /*
             * System.out.println(String.valueOf(attrs.get("CN")));
             * System.out.println(String.valueOf(attrs.get("sAMAccountName")));
             * System.out.println(String.valueOf(attrs.get("description")));
             * System.out.println(String.valueOf(attrs.get("SN")));
             * System.out.println(String.valueOf(attrs.get("userPrincipalName")));
             * System.out.println(String.valueOf(attrs.get("primaryGroupID")));
             * System.out.println(String.valueOf(attrs.get("objectCategory")));
             * System.out.println(String.valueOf(attrs.get("distinguishedName")));
             * System.out.println(String.valueOf(attrs.get("homeDirectory")));
             * System.out.println(String.valueOf(attrs.get("givenName")));
             * System.out.println(String.valueOf(attrs.get("mail")));
             * System.out.println(String.valueOf(attrs.get("displayName")));
             * System.out.println(String.valueOf(attrs.get("Codigo")));
             * System.out.println(String.valueOf(attrs.get("cod")));
             * System.out.println(String.valueOf(attrs.get("id")));
             */
            /*
             * System.out.println(); NamingEnumeration<? extends Attribute> at =
             * attrs.getAll(); while (at.hasMore()) {
             * System.out.println(at.next()); }
             */

        } catch (javax.naming.CommunicationException uhe) {
            usuario = null;
//throw new AutenticacaoException("Falha ao Cominicar com o host do"+
//" Servidor LDAP : " + host + " na porta "+ porta +", por favor verifique a sintaxe :: "+ uhe.getMessage());
            uhe.printStackTrace();
            return false;
        } catch (AuthenticationException ae) {
            usuario = null;
            System.out.println("Falha ao autenticar o usuário"
                    + " no Servidor LDAP :" + host + ", Usuário e/ou Senha errado(s) ! :: " + ae.getMessage());
            return false;
        } catch (Exception e) {
            usuario = null;
            e.printStackTrace();
            return false;
        }

        if (contexto != null) {
            try {
                contexto.close();
            } catch (NamingException ex) {
                System.out.println("Erro ao fechar contexto ! : " + ex.getMessage());
            }
        }

        return true;
    }

    public static String[] dadosLDAP(String usuario, String senha, String host, int porta, boolean ssl) {
        DirContext contexto = null;
        if (porta == 0) {
            porta = 389;
        }
        String s[] = new String[3];

        try {
            Hashtable props = new Hashtable(11);

            props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

            if (ssl) {
                props.put(Context.PROVIDER_URL, "ldap://" + host + ":" + porta + "");
                props.put(Context.SECURITY_PROTOCOL, "ssl");
                props.put(Context.SECURITY_AUTHENTICATION, "EXTERNAL");

                System.setProperty("javax.net.ssl.keyStore", "ctti1");
                System.setProperty("javax.net.ssl.trustStorePassword", "ctti2011");

            } else {
                props.put(Context.PROVIDER_URL, "ldap://" + host + ":" + porta + "");
                props.put(Context.SECURITY_AUTHENTICATION, "simple");
            }

            props.put(Context.SECURITY_PRINCIPAL, usuario);
            props.put(Context.SECURITY_CREDENTIALS, senha);

            SSLServerSocketFactory.getDefault();

            DirContext ctx = new InitialDirContext(props);


            contexto = ctx;
            Attributes attrs = ctx.getAttributes(usuario);

            s[0] = String.valueOf(attrs.get("codAluno"));
            s[1] = String.valueOf(attrs.get("displayName"));
            s[2] = String.valueOf(attrs.get("uid"));

            /*
             * System.out.println(String.valueOf(attrs.get("CN")));
             * System.out.println(String.valueOf(attrs.get("sAMAccountName")));
             * System.out.println(String.valueOf(attrs.get("description")));
             * System.out.println(String.valueOf(attrs.get("SN")));
             * System.out.println(String.valueOf(attrs.get("userPrincipalName")));
             * System.out.println(String.valueOf(attrs.get("primaryGroupID")));
             * System.out.println(String.valueOf(attrs.get("objectCategory")));
             * System.out.println(String.valueOf(attrs.get("distinguishedName")));
             * System.out.println(String.valueOf(attrs.get("homeDirectory")));
             * System.out.println(String.valueOf(attrs.get("givenName")));
             * System.out.println(String.valueOf(attrs.get("mail")));
             *
             * System.out.println(String.valueOf(attrs.get("Codigo")));
             * System.out.println(String.valueOf(attrs.get("cod")));
             * System.out.println(String.valueOf(attrs.get("id")));
             */
            /*
             * System.out.println(); NamingEnumeration<? extends Attribute> at =
             * attrs.getAll(); while (at.hasMore()) {
             * System.out.println(at.next()); }
             */

        } catch (javax.naming.CommunicationException uhe) {
            usuario = null;
//throw new AutenticacaoException("Falha ao Cominicar com o host do"+
//" Servidor LDAP : " + host + " na porta "+ porta +", por favor verifique a sintaxe :: "+ uhe.getMessage());
            uhe.printStackTrace();
            return s;
        } catch (AuthenticationException ae) {
            usuario = null;
            System.out.println("Falha ao autenticar o usuário"
                    + " no Servidor LDAP :" + host + ", Usuário e/ou Senha errado(s) ! :: " + ae.getMessage());
            return s;
        } catch (Exception e) {
            usuario = null;
            e.printStackTrace();
            return s;
        }

        if (contexto != null) {
            try {
                contexto.close();
            } catch (NamingException ex) {
                System.out.println("Erro ao fechar contexto ! : " + ex.getMessage());
            }
        }

        return s;
    }

    public static Vector importarPessoaVectorByte(File arquivo) throws Exception {
        String linha = "";

        Vector linhas = new Vector();
        Vector colunas = new Vector();

        FileInputStream fi = new FileInputStream(arquivo);
        BufferedInputStream in = new BufferedInputStream(fi);
        int x;
        while ((x = in.read()) != -1) {
            linha = linha + (char) x;
            if (x != 10) {
                continue;
            }
            try {
                String[] p = linha.replace("\"", "").replace("'", "").split(";");
                colunas.add(p[0].trim());
                colunas.add(p[1].trim());
                try {
                    colunas.add(p[2].trim());
                } catch (Exception ex) {
                    colunas.add("-");
                }
                linhas.add(new Vector(colunas));
                colunas.removeAllElements();
            } catch (Exception e) {
            }
            linha = "";
        }

        in.close();

        return linhas;
    }

    public static String abrirArquivo(File arquivo) throws Exception {

        String ret = "";
        String linha;
        BufferedReader bf = new BufferedReader(new FileReader(arquivo));
        linha = bf.readLine();
        ret += linha;
        while ((linha = bf.readLine()) != null) {
            ret += "\n" + linha;
        }
        return ret;


    }

    public static void gravarArquivo(File arquivo, String mensagem) {
        try {
            FileWriter fr = new FileWriter(arquivo);
            PrintWriter pr = new PrintWriter(fr);
            pr.print(mensagem);
            pr.close();
            fr.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean salvarImagens(BufferedImage[] imagens, String[] nImagens) {
        if (imagens.length == nImagens.length) {
            try {
                for (int i = 0; i < imagens.length; i++) {
                    ImageIO.write((BufferedImage) imagens[i],
                            nImagens[i].substring(nImagens[i].lastIndexOf(".") + 1),
                            new File(nImagens[i]));
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    public static boolean apagarImagens(String[] nImagens) {
        try {
            for (int i = 0; i < nImagens.length; i++) {
                File f = new File(nImagens[i]);
                f.delete();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String lerString(Component comp, String aviso, String padrao) {
        return JOptionPane.showInputDialog(comp, aviso, padrao);
    }

    public static String lerSenha(Component comp, String aviso) {
        JPasswordField pwd = new JPasswordField();
        Object[] message = {aviso, pwd};
        int resposta = JOptionPane.showConfirmDialog(comp, message, "Password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (resposta == JOptionPane.OK_OPTION) {
            String pass = new String(pwd.getPassword());
            return pass;
        }
        return null;
    }

    public static void aviso(Component comp, String aviso) {
        aviso(comp, aviso, "Aviso");
    }

    public static void aviso(Component comp, String aviso, String titulo) {
        JOptionPane.showMessageDialog(comp, aviso, titulo, JOptionPane.INFORMATION_MESSAGE);
    }

    public static void erro(Component comp, String aviso) {
        erro(comp, aviso, "Erro");
    }

    public static void erro(Component comp, String aviso, String titulo) {
        JOptionPane.showMessageDialog(comp, aviso, titulo, JOptionPane.ERROR_MESSAGE);
    }

    public static boolean confirmar(Component comp, String aviso) {
        return confirmar(comp, aviso, "Confirmar");
    }

    public static boolean confirmar(Component comp, String aviso, String titulo) {
        Object[] options = {"Sim", "Não"};
        int i = JOptionPane.showOptionDialog(comp,
                aviso, titulo,
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                options, options[1]);

        if (i == JOptionPane.YES_OPTION) {
            return true;
        }
        return false;
    }

    public static String paraHora(Date data) {
        return formatterDATAhora.format(data);
    }

    public static Date paraHora(String dt) {
        try {
            Date data = new Date(formatterDATAhora.parse(dt).getTime());
            return data;
        } catch (Exception e) {
            //e.printStackTrace();
            try {
                Date data = new Date(formatterDATAhora1.parse(dt).getTime());
                return data;
            } catch (Exception ex) {
                e.printStackTrace();
                ex.printStackTrace();
                return null;
            }
        }
    }

    public static Date paraData(String dt) {
        dt = dt.replace("\\", "/").replace(".", "/").replace(";", "/");
        try {
            Date data = new Date(formatterDATA.parse(dt).getTime());
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            try {
                Date data = new Date(formatterDATA1.parse(dt).getTime());
                return data;
            } catch (Exception ex) {
                ex.printStackTrace();
                try {
                    Date data = new Date(formatterSQL.parse(dt).getTime());
                    return data;
                } catch (Exception exc) {
                    exc.printStackTrace();
                    return null;
                }
            }
        }
    }

    public static String paraData(Date data) {
        return formatterDATA.format(data);
    }

    public static String cripMD5(String sCrip) {
        try {
            String ret = "";
            MessageDigest md;
            md = MessageDigest.getInstance("MD5");
            md.update(sCrip.getBytes());
            BigInteger hash = new BigInteger(1, md.digest());
            ret = hash.toString(16);

            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String criptografar(String sCrip) {
        String ret = "";
        int ch;
        for (int i = 0; i < (sCrip.length()); i++) {
            ch = (int) (sCrip.charAt(i));
            byte c = (byte) (ch + key);
            char d = (char) (c);
            ret += d;
        }
        return ret;
    }

    public static String descriptografar(String sCrip) {
        String ret = "";
        int ch;
        for (int i = 0; i < (sCrip.length()); i++) {
            ch = (int) (sCrip.charAt(i));
            byte c = (byte) (ch - key);
            char d = (char) (c);
            ret += d;
        }
        return ret;
    }

    public static boolean paraBoolean(String bo) {
        if (bo.equalsIgnoreCase("nao")) {
            return false;
        } else if (bo.equalsIgnoreCase("não")) {
            return false;
        } else if (bo.equalsIgnoreCase("false")) {
            return false;
        } else if (bo.equalsIgnoreCase("sim")) {
            return true;
        } else if (bo.equalsIgnoreCase("true")) {
            return true;
        } else if (bo.equalsIgnoreCase("yes")) {
            return true;
        } else if (bo.equalsIgnoreCase("no")) {
            return true;
        } else {
            return false;
        }
    }

    public static String paraBoolean(boolean bo) {
        if (bo) {
            return "sim";
        } else {
            return "não";
        }
    }

    public static boolean verificaCPF(String cpf) {
        boolean retorno = false;
        try {
            cpf = soNumeros(cpf);
            int cpf1 = Integer.parseInt(cpf.substring(0, 1));
            int cpf2 = Integer.parseInt(cpf.substring(1, 2));
            int cpf3 = Integer.parseInt(cpf.substring(2, 3));
            int cpf4 = Integer.parseInt(cpf.substring(3, 4));
            int cpf5 = Integer.parseInt(cpf.substring(4, 5));
            int cpf6 = Integer.parseInt(cpf.substring(5, 6));
            int cpf7 = Integer.parseInt(cpf.substring(6, 7));
            int cpf8 = Integer.parseInt(cpf.substring(7, 8));
            int cpf9 = Integer.parseInt(cpf.substring(8, 9));
            int cpf10 = Integer.parseInt(cpf.substring(9, 10));
            int cpf11 = Integer.parseInt(cpf.substring(10, 11));
            int dv1 = (cpf1 * 10 + cpf2 * 9 + cpf3 * 8 + cpf4 * 7 + cpf5 * 6 + cpf6 * 5 + cpf7 * 4 + cpf8 * 3 + cpf9 * 2) % 11;
            if (dv1 < 2) {
                dv1 = 0;
            } else {
                dv1 = 11 - dv1;
            }
            int dv2 = (cpf1 * 11 + cpf2 * 10 + cpf3 * 9 + cpf4 * 8 + cpf5 * 7 + cpf6 * 6 + cpf7 * 5 + cpf8 * 4 + cpf9 * 3 + dv1 * 2) % 11;
            if (dv2 < 2) {
                dv2 = 0;
            } else {
                dv2 = 11 - dv2;
            }
            if (dv1 == cpf10 && dv2 == cpf11) {
                retorno = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            retorno = false;
        }
        return retorno;
    }

    public static boolean verificaCNPJ(String cnpj) {


        int VAR1 = 0, VAR2 = 0, VAR3 = 0, VAR4 = 0, VAR5 = 0;

        String sCNPJ = null;

        boolean ret = false;

//retirar caracteres inválidos e deixar somente números
        sCNPJ = soNumeros(cnpj);

        if (sCNPJ.length() == 8) {
            VAR1 = 0;
            VAR2 = 0;
            VAR4 = 0;
            for (VAR3 = 1; VAR3 < 8; VAR3++) {
                VAR1 = Integer.parseInt(sCNPJ.substring(1, VAR3));
                VAR1 = VAR1 % 2;
                if (VAR1 != 0) {
                    VAR1 = VAR1 * 2;
                }
                if (VAR1 > 9) {
                    VAR2 = VAR2 + (VAR1 / 10) + (VAR1 = VAR1 % 10);
                } else {
                    VAR2 = VAR2 + VAR1;
                }
            }
            VAR2 = VAR2 % 10;
            if (VAR2 != 0) {
                VAR4 = 10 - VAR2;
            } else {
                VAR4 = 0;
            }

            if (VAR4 == (Integer.parseInt(sCNPJ.substring(1, 8)))) {
                return true;
            } else {
                return false;
            }
        } else {
            if (sCNPJ.length() == 14) {
                VAR1 = 0;
                VAR3 = 0;
                VAR4 = 0;
                VAR5 = 0;
                VAR2 = 5;
                for (VAR3 = 0; VAR3 <= 11; VAR3++) {
                    VAR1 = VAR1 + ((Integer.parseInt(sCNPJ.substring(VAR3, VAR3 + 1)) * VAR2));
                    VAR2 = (VAR2 > 2) ? VAR2 - 1 : 9;
                }
                VAR1 = VAR1 % 11;
                VAR4 = (VAR1 > 1) ? 11 - VAR1 : 0;
                VAR1 = 0;
                VAR3 = 0;
                VAR2 = 6;
                for (VAR3 = 0; VAR3 <= 12; VAR3++) {
                    VAR1 = VAR1 + ((Integer.parseInt(sCNPJ.substring(VAR3, VAR3 + 1)) * VAR2));
                    VAR2 = (VAR2 > 2) ? VAR2 - 1 : 9;
                }
                VAR1 = VAR1 % 11;
                VAR5 = (VAR1 > 1) ? 11 - VAR1 : 0;
                if ((VAR4 == Integer.parseInt(sCNPJ.substring(12, 13))) && (VAR5 == Integer.parseInt(sCNPJ.substring(13, 14)))) {
                    return true;
                } else {
                    return false;
                }

            } else {
                return false;
            }
        }

    }

    public static String soLetras(String orig) {
        for (int i = 0; i < orig.length(); i++) {
            int c = (int) orig.charAt(i);
            if (c < 65 || (c > 90 && c < 97) || c > 122) {
                orig = orig.replace(orig.charAt(i) + "", "");
                i--;
            }
        }
        return orig;
    }

    public static String soNumeros(String orig) {
        for (int i = 0; i < orig.length(); i++) {
            int c = (int) orig.charAt(i);
            if (c < 48 || c > 57) {
                orig = orig.replace(orig.charAt(i) + "", "");
                i--;
            }
        }
        return orig;
    }

    public static File gravaArquivoDeURL(String stringUrl, String nomeArquivoLocal) {
        try {

            //Encapsula a URL num objeto java.net.URL
            URL url = new URL(stringUrl);

            //Queremos o arquivo local com o mesmo nome descrito na URL
            //Lembrando que o URL.getPath() ira retornar a estrutura
            //completa de diretorios e voce deve tratar esta String
            //caso nao deseje preservar esta estrutura no seu disco local.

            //Cria streams de leitura (este metodo ja faz a conexao)...
            InputStream is = url.openStream();

            //... e de escrita.
            FileOutputStream fos = new FileOutputStream(nomeArquivoLocal);

            //Le e grava byte a byte. Voce pode (e deve) usar buffers para
            //melhor performance (BufferedReader).
            int umByte = 0;
            while ((umByte = is.read()) != -1) {
                fos.write(umByte);
            }

            //Nao se esqueca de sempre fechar as streams apos seu uso!
            is.close();
            fos.close();

            //apos criar o arquivo fisico, retorna referencia para o mesmo
            return new File(nomeArquivoLocal);

        } catch (Exception e) {
            //Lembre-se de tratar bem suas excecoes, ou elas tambem lhe tratarão mal!
            //Aqui so vamos mostrar o stack no stderr.
            //Log.addAviso(e, "Arquivo para download não existe");
        }

        return null;
    }
}
